const app = new Vue({
  el: '#app',
  data() {
    // 校验学号是否存在
    const rulesSNo = (rule, value, callback) => {
      if (this.isEdit) {
        callback();
      }
      //使用Axios进行校验
      axios.post(
        this.baseURL + "students/check_sno",
        {
          sno: value,
        }
      )
        .then((res) => {
          // 请求成功
          if (res.data.code === 1) {
            if (res.data.exists) {
              callback(new Error("学号已存在"));
            } else {
              callback();
            }
          } else {
            // 请求失败
            callback(new Error("校验学号后端出现 异常"));
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }
    return {
      msg: 'Hello, Vue!',
      students: [],
      pageStudents: [], // 分页后当前页的学生
      baseURL: "http://192.168.56.1:8000/",
      inputStr: '', // 输入的查询条件
      selectedStudents: [],  // 复选框选中的学生
      // === 分页相关的变量 ===
      total: 0,  // 数据的总行数
      currentpage: 1,  // 当前的页面
      pagesize: 10,  // 每页显示多少行

      // === 弹出框 ===
      dialogVisible: false,
      dialogTitle: "",
      isView: false,  // 标识是否能查看
      isEdit: false,  // 标识是否能修改
      // === 学生信息 ===
      studentForm: {
        sno: '',
        name: '',
        gender: '',
        birthday: '',
        mobile: '',
        email: '',
        address: '',
        image: '',
        imageUrl: '',
      },

      rules: {
        sno: [
          { required: true, message: '学号不能为空', trigger: 'blur' },
          { pattern: /^[9][5]\d{3}$/, message: '学号必须为95开头的5个数字', trigger: 'blur' },
          { validator: rulesSNo, trigger: 'blur' },  // 后端校验学号是否存在
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '姓名必须是2-5个汉字', trigger: 'blur' },
        ],
        gender: [
          { required: true, message: '性别不能为空', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '出生日期不能为空', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^[1][35789]\d{9}$/, message: '手机号码必须要符合规范', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]w+)*$/ }
        ],
        address: [
          { required: true, message: '住址不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  mounted() {
    // 自动加载数据
    this.getStudents();
  },
  methods: {
    // ====    ====    ==== 页面整体 ====    ====    ====
    // 从数据库获取所有学生信息
    getStudents: function () {
      // 记录this地址, 因为axios之后，this变成undefined !!
      let that = this
      // 使用Axios实现Ajax请求
      axios
        .get(that.baseURL + "students/get")
        .then(function (res) {
          // 请求成功后执行的函数
          // console.log(res);
          if (res.data.code === 1) {
            // 把数据给students
            that.students = res.data.data;
            // 获取返回记录的总行数
            that.total = res.data.data.length;
            // 获取当前页的数据
            that.getPageStudents();
            // 提示:
            that.$message({
              message: '数据加载成功!',
              type: 'success'
            });
            console.log(that.students);
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch(function (err) {
          // 请求失败后执行的函数
          console.log(err);
        })

    },
    getAllStudents() {
      // 清空输入的inputStr
      this.inputStr = "";
      this.getStudents();
    },
    // 获取当前页的学生数据
    getPageStudents() {
      // 清空pageStudents中的数据
      this.pageStudents = [];
      // 获得当前页的数据
      for (let i = (this.currentpage - 1) * this.pagesize; i < this.total; i++) {
        // 把遍历数据添加到pageStudent中
        this.pageStudents.push(this.students[i]);
        //判断是否达到一页的要求
        if (this.pageStudents.length === this.pagesize) break;
      }
    },
    // 分页时更新每页的行数
    handleSizeChange(size) {
      // 更新当前页数据
      this.pagesize = size;
      // 数据重新分页
      this.getPageStudents();
    },
    // 调整当前的页码
    handleCurrentChange(pageNumber) {
      this.currentpage = pageNumber;
      // 数据重新分页
      this.getPageStudents();
    },
    // 实现学生信息查询
    queryStudents() {
      // 使用Ajax请求 -- POST -- 传递 inputStr
      let that = this
      axios
        .post(
          that.baseURL + "students/query",
          {
            inputstr: that.inputStr
          }
        )
        .then(function (res) {
          if (res.data.code === 1) {
            that.students = res.data.data;
            that.total = res.data.data.length;
            that.getPageStudents();
            that.$message({
              message: '数据查询成功!',
              type: 'success'
            })
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch(function (err) {
          console.log(err);
          that.$message.error("获取后端查询结果出现异常!");
        });
    },
    // ====    ====    ==== 单个增，查，改 ====    ====    ====
    // 点击‘添加学生’时打开对话框表单
    addStudent() {
      // 修改标题
      this.dialogTitle = "添加学生明细"
      this.dialogVisible = true;
    },
    // 根据Id获取image
    getImageBySno(sno) {
      // 遍历
      for (one of this.students) {
        if (one.sno == sno) {
          return one.image;
        }
      }
    },
    // 查看学生的明细
    viewStudent(row) {
      // 修改标题
      this.dialogTitle = "查看学生明细"
      this.isView = true;
      // 弹出表单
      this.dialogVisible = true;
      // 赋值，深拷贝
      this.studentForm = JSON.parse(JSON.stringify(row));
      // 获取照片
      this.studentForm.image = this.getImageBySno(row.sno);
      // 获取照片的url
      this.studentForm.imageUrl = this.baseURL + 'media/' + this.studentForm.image;
    },
    // 关闭弹出框时表单清空
    closeDialogForm(formName) {
      // 重置表单的校验
      this.$refs[formName].resetFields();
      // 清空表单
      this.studentForm.sno = '';
      this.studentForm.name = '';
      this.studentForm.gender = '';
      this.studentForm.birthday = '';
      this.studentForm.mobile = '';
      this.studentForm.email = '';
      this.studentForm.address = '';
      this.studentForm.mobile = '';
      this.studentForm.image = '';
      this.studentForm.imageUrl = '';
      this.dialogVisible = false;
      this.isEdit = false;
      this.isView = false;
    },
    // 修改学生的明细
    updateStudent(row) {
      // 修改标题
      this.dialogTitle = "修改学生明细";
      this.isEdit = true;
      // 弹出表单
      this.dialogVisible = true;
      this.studentForm = JSON.parse(JSON.stringify(row));
      // 获取照片
      this.studentForm.image = this.getImageBySno(row.sno);
      // 获取照片的url
      this.studentForm.imageUrl = this.baseURL + 'media/' + this.studentForm.image;
    },
    // 提交学生的表单
    submitStudentForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验成功后执行添加或修改
          if (this.isEdit) {
            // 修改
            this.submitUpdateStudent();
          } else {
            // 添加
            this.submitAddStudent();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加到数据库的函数
    submitAddStudent() {
      // 定义that
      let that = this;
      // 执行Axios请求
      axios
        .post(this.baseURL + "students/add", that.studentForm)
        .then(res => {
          // 执行成功
          if (res.data.code === 1) {
            // 获取所有学生信息
            that.students = res.data.data;
            that.total = res.data.data.length;
            that.getPageStudents();
            that.$message({
              message: '数据添加成功',
              type: 'success'
            });
            // 关闭窗体
            that.closeDialogForm('studentForm');
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch(err => {
          // 失败
          console.log(err);
          that.$message.error("获取后端查询结果出现异常!");
        })
    },
    // 修改到数据库的函数
    submitUpdateStudent() {
      // 定义that
      let that = this;
      // 执行Axios请求
      axios
        .post(this.baseURL + "students/update", that.studentForm)
        .then(res => {
          // 执行成功
          if (res.data.code === 1) {
            // 获取所有学生信息
            that.students = res.data.data;
            that.total = res.data.data.length;
            that.getPageStudents();
            that.$message({
              message: '数据修改成功',
              type: 'success'
            });
            // 关闭窗体
            that.closeDialogForm('studentForm');
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch(err => {
          // 失败
          console.log(err);
          that.$message.error("修改时获取后端查询结果出现异常!");
        })
    },
    // ====    ====    ==== 删除 ====    ====    ====
    // 单条删除
    deleteStudent(row) {
      // 等待确认
      this.$confirm('此操作将永久删除' + row.sno + '\t姓名: ' + row.name + '学生信息, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除
        let that = this
        // 调用后端接口
        axios.post(that.baseURL + "students/delete", { sno: row.sno })
          .then(res => {
            if (res.data.code === 1) {
              // 获取所有学生信息
              that.students = res.data.data;
              // 获取记录数
              that.total = res.data.data.length;
              // 分页
              that.getPageStudents();
              that.$message({
                message: '数据删除成功！',
                type: 'success'
              });
            } else {
              that.$message.error(res.data.msg);
            }
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 选择复选框时的操作
    handleSelectionChange(data) {
      this.selectedStudents = data;
      console.log(data);
    },
    // 多条删除
    deleteStudents() {
      // 等待确认
      this.$confirm('此操作将批量删除' + this.selectedStudents.length + '个学生信息, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除
        let that = this
        // 调用后端接口
        axios.post(that.baseURL + "students/delete_multi", { student: that.selectedStudents })
          .then(res => {
            if (res.data.code === 1) {
              // 获取所有学生信息
              that.students = res.data.data;
              // 获取记录数
              that.total = res.data.data.length;
              // 分页
              that.getPageStudents();
              that.$message({
                message: '数据批量删除成功！',
                type: 'success'
              });
            } else {
              that.$message.error(res.data.msg);
            }
          })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 选择学生头像后点击确定后触发的事件
    uploadPicturePost(file) {
      // 定义that
      let that = this;
      // 定义一个FormData类
      let fileReq = new FormData();
      // 把照片传进去
      fileReq.append('avatar', file.file);
      // 使用Axios发起Ajax请求
      axios(
        {
          method: 'post',
          url: that.baseURL + 'students/upload',
          data: fileReq
        }
      ).then(res => {
        // 根据code判断是否成功
        if (res.data.code === 1) {
          // 把照片名字给image
          that.studentForm.image = res.data.name;
          // 拼接imageurl
          that.studentForm.imageUrl = that.baseURL + "media/" + res.data.name;
        } else {
          that.$message.error(res.data.msg);
        }
      }).catch(err => {
        console.log(err);
        that.$message.error("上传头像后台出现异常！");
      })

    },
    // ====    ====    ==== 导入Excel上传数据 ====    ====    ====
    uploadExcelPost(file) {
      let that = this;
      // 实例化FormData
      let fileReq = new FormData();
      fileReq.append('excel', file.file);
      // 使用Axios发起Ajax请求
      axios(
        {
          method: 'post',
          url: that.baseURL + 'students/excel_import',
          data: fileReq
        }
      ).then(res => {
        // 根据code判断是否成功
        if (res.data.code === 1) {
          // 
          that.students = res.data.data;
          // 计算总共多少条
          that.total = res.data.data.length;
          // 分页
          that.getPageStudents();
          // 弹出框
          this.$alert('本次导入完成！成功：' + res.data.success + '失败' + res.data.error, '导入结果展示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: '本次导入失败数量为: ' + res.data.error + ',学号: ' + res.data.errors
              });
            }
          });
          // 失败明细
          console.log('本次导入失败的学号: ');
          console.log(res.data.errors);
        } else {
          that.$message.error(res.data.msg);
        }
      }).catch(err => {
        console.log(err);
        that.$message.error("上传Excel后台出现异常！");
      })
    },
    // 导出excel
    exportExcel() {
      let that = this;
      axios.get(that.baseURL + 'students/excel_export')
        .then(res => {
          if (res.data.code === 1) {
            // 拼接excel的完整URL
            let url = that.baseURL + 'media/' + res.data.name;
            // 下载
            window.open(url);
          } else {
            // 前端出现问题
            that.$message.error("导出Excel出现异常:" + res.data.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
  }
})